import React, { useEffect, useLayoutEffect, useRef } from "react"; // 添加 useRef 导入
import {
  Drawer,
  Form,
  Input,
  InputNumber,
  Button,
  Cascader,
  Space,
  Typography,
  Flex,
  message,
  FormInstance,
} from "antd";
import { EnvironmentOutlined, CaretDownOutlined } from "@ant-design/icons";
import { errorHandler } from "@/common/common";
import DynamicForm from "@/components/DynamicForm";
import { createDeviceInfoFeildField } from "./deviceListsFields";
import { DynamicFormRef, Fields } from "@/types/public"; // 导入 DynamicFormRef 类型
import convertTypes from "@/common/convertTypes";
interface AddProjectDrawerProps {
  visible: boolean;
  onClose: () => void;
  columns: Fields[];
  onSubmit: (values: any) => Promise<void>;
  initialData?: Record<string, any>;
  mode?: "create" | "edit";
}
const { Text } = Typography;

// ... 省略其他代码 ...
const AddProjectDrawer: React.FC<AddProjectDrawerProps> = ({
  visible,
  onClose,
  columns,
  onSubmit,
  initialData,
  mode = "create",
}) => {
  const dynamicFormRef = useRef<DynamicFormRef>(null); // 创建 ref 引用 DynamicForm
  const [loading, setLoading] = React.useState(false);

  if (initialData) mode = "edit";

  useEffect(() => {
    if (visible) {
      if (initialData) {
        dynamicFormRef.current?.form?.setFieldsValue(initialData);
      } else {
        dynamicFormRef.current?.form?.resetFields();
      }
    }
  }, [visible, initialData]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      // 通过 ref 获取 DynamicForm 的表单实例并验证字段
      const values = await dynamicFormRef.current?.form.validateFields();
      if (values) {
        await onSubmit(convertTypes(columns, values));
      }
    } catch (error) {
      console.error(error);
      errorHandler(error);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    dynamicFormRef.current?.form?.resetFields();
    onClose();
  };

  return (
    <Drawer
      title={mode === "edit" ? "编辑项目" : "添加项目"}
      width={"40%"}
      open={visible}
      onClose={handleClose}
      placement="right"
      extra={
        <Space>
          <Button onClick={handleClose}>取消</Button>
          <Button type="primary" onClick={handleSubmit} loading={loading}>
            {mode === "edit" ? "更新" : "保存"}
          </Button>
        </Space>
      }
    >
      {/* 将 ref 传递给 DynamicForm */}
      <DynamicForm
        ref={dynamicFormRef}
        formItems={columns as []}
        layout="vertical"
      />
    </Drawer>
  );
};

export default AddProjectDrawer;
